/**
 * Created with hong.rong
 * Date:2020/07/05
 */

import React, { useState, useEffect, createContext } from 'react'
import { getListLevel } from '@/services/config/category'
import { CATEGORY_LEVEL } from '@/constant/category'

// 创建 context
export const CategoryContext = createContext({})

export default function CategoryWrapper(props) {
  const [levelOne, setLevelOne] = useState([])
  const [levelTwo, setLevelTwo] = useState([])

  useEffect(() => {
    async function getOptions() {
      await fetchLevelData(CATEGORY_LEVEL.ONE, undefined)
    }
    getOptions()
  }, [])

  /**
   * 获取层级数据
   * @param cateLevel
   * @param pid
   * @returns {Promise<void>}
   */
  const fetchLevelData = async (cateLevel, pid) => {
    const { data = {} } = await getListLevel({ cateLevel, pid })
    if (data && data.code === 0) {
      const list = data.data || []
      switch (cateLevel) {
        case CATEGORY_LEVEL.ONE:
          setLevelOne(list)
          break
        case CATEGORY_LEVEL.TWO:
          setLevelTwo(list)
          break
        default:
          break
      }
    }
  }

  return (
    <CategoryContext.Provider
      value={{
        levelOne,
        levelTwo,
        fetchLevelData,
      }}
    >
      {props.children}
    </CategoryContext.Provider>
  )
}
